package thread.forkjoinpool;

import java.util.concurrent.RecursiveTask;

public class MyRecursiveTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 50;

    private final int start;

    private final int end;

    public MyRecursiveTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if (end - start < THRESHOLD) {
            // 重复的数据取在首部的
            for (int i = start; i < end; i++) {
                System.out.println("线程:" + Thread.currentThread().getName() + " i的值为:" + i + " time:" + System.currentTimeMillis());

                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            System.out.println("middle:" + middle);
            MyRecursiveTask left = new MyRecursiveTask(start, middle);
            MyRecursiveTask right = new MyRecursiveTask(middle, end);
            left.fork();
            right.fork();
            int a = left.join();
            int b = right.join();
            sum = a + b;
        }
        return sum;
    }
}
